package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class PersonServlet
 */
@WebServlet(urlPatterns = { "/Person", "/person", "/PersonServlet", "/personServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class PersonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public PersonServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<PersonModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("personNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			PersonModel query = new PersonModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());

			PersonModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("person", obj);
				getServletContext().getRequestDispatcher("/personEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			PersonModel query = new PersonModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());

			PersonModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("person", obj);
				response.sendRedirect("personView.jsp");

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			PersonModel obj = new PersonModel();

			// SET NAME here

			GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());
			int res = 0;

			try {
				String strName = request.getParameter("first_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setFirstName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("person", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			PersonModel query = new PersonModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("personList.jsp");
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			PersonModel obj = new PersonModel();
//			String is_employee = request.getParameter("is_employee");
//					obj.setIsEmployee(is_employee.equalsIgnoreCase("true")
//							|| is_employee.equalsIgnoreCase("1"));

String first_name = request.getParameter("first_name");
					obj.setFirstName(first_name);

String last_name = request.getParameter("last_name");
					obj.setLastName(last_name);

String mobile = request.getParameter("mobile");
					obj.setMobile(mobile);

String company_phone = request.getParameter("company_phone");
					obj.setCompanyPhone(company_phone);

String home_phone = request.getParameter("home_phone");
					obj.setHomePhone(home_phone);

String company_email = request.getParameter("company_email");
					obj.setCompanyEmail(company_email);

String personal_email = request.getParameter("personal_email");
					obj.setPersonalEmail(personal_email);

String address = request.getParameter("address");
					obj.setAddress(address);


String birthdate_date = request.getParameter("birthdate_date");
    String birthdate_time = request.getParameter("birthdate_time");
    if (birthdate_date != null && !birthdate_date.isEmpty() && birthdate_time != null && !birthdate_time.isEmpty()) {
            obj.setBirthdate(DateTimeUtil.parseDateTime(birthdate_date, birthdate_time));
} else {
    obj.setBirthdate(DateTimeUtil.parseDate(birthdate_date));
}

String identity_no = request.getParameter("identity_no");
					obj.setIdentityNo(identity_no);

String gender = request.getParameter("gender");

	if(gender.equals("1"))
		obj.setGender(true);
	if(gender.equals("2"))
		obj.setGender(false);
	
					
String description = request.getParameter("description");
					obj.setDescription(description);

String status = request.getParameter("status");
                    if (status != null && !status.isEmpty()) {
					    obj.setStatus(Integer.parseInt(status));
                    }

//String is_draft = request.getParameter("is_draft");
//					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//							|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }



String middle_name = request.getParameter("middle_name");
					obj.setMiddleName(middle_name);

String id_employee = request.getParameter("id_employee");
                    if (id_employee != null && !id_employee.isEmpty()) {
					    obj.setIdEmployee(Integer.parseInt(id_employee));
                    }

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, refresh cache and redirect to somewhere
					response.sendRedirect("personNew.jsp");
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("person", obj);
				getServletContext().getRequestDispatcher("/personInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			PersonModel query = new PersonModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());

			PersonModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				
//				String is_employee = request.getParameter("is_employee");
//					obj.setIsEmployee(is_employee.equalsIgnoreCase("true")
//							|| is_employee.equalsIgnoreCase("1"));

String first_name = request.getParameter("first_name");
					obj.setFirstName(first_name);

String last_name = request.getParameter("last_name");
					obj.setLastName(last_name);

String mobile = request.getParameter("mobile");
					obj.setMobile(mobile);

String company_phone = request.getParameter("company_phone");
					obj.setCompanyPhone(company_phone);

String home_phone = request.getParameter("home_phone");
					obj.setHomePhone(home_phone);

String company_email = request.getParameter("company_email");
					obj.setCompanyEmail(company_email);

String personal_email = request.getParameter("personal_email");
					obj.setPersonalEmail(personal_email);

String address = request.getParameter("address");
					obj.setAddress(address);


String birthdate_date = request.getParameter("birthdate_date");
    String birthdate_time = request.getParameter("birthdate_time");
    if (birthdate_date != null && !birthdate_date.isEmpty() && birthdate_time != null && !birthdate_time.isEmpty()) {
            obj.setBirthdate(DateTimeUtil.parseDateTime(birthdate_date, birthdate_time));
} else {
    obj.setBirthdate(DateTimeUtil.parseDate(birthdate_date));
}

String identity_no = request.getParameter("identity_no");
					obj.setIdentityNo(identity_no);

String gender = request.getParameter("gender");
					obj.setGender(gender.equalsIgnoreCase("true")
							|| gender.equalsIgnoreCase("1"));

String description = request.getParameter("description");
					obj.setDescription(description);

String status = request.getParameter("status");
                    if (status != null && !status.isEmpty()) {
					    obj.setStatus(Integer.parseInt(status));
                    }

//String is_draft = request.getParameter("is_draft");
//					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//							|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }



String middle_name = request.getParameter("middle_name");
					obj.setMiddleName(middle_name);

String id_employee = request.getParameter("id_employee");
                    if (id_employee != null && !id_employee.isEmpty()) {
					    obj.setIdEmployee(Integer.parseInt(id_employee));
                    }

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("personList.jsp");
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("person", obj);
					getServletContext().getRequestDispatcher("/personList.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			PersonModel obj = new PersonModel();

			// SET NAME here

			GenericDal<PersonModel, PersonModelExt> dal = new GenericDal<PersonModel, PersonModelExt>(new PersonModel());
			int res = 0;

			try {
				String strName = request.getParameter("first_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setFirstName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("person", "" + res);
					out.println(resultXML);
				}
				else
				{
					//TODO: respone something
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}